<template>
  <div class="admin-activity-management">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <h1 class="page-title">活动管理</h1>
        <p class="page-subtitle">管理系统中的所有活动</p>
      </div>
      <div class="header-actions">
        <el-button @click="exportData">
          <el-icon><Download /></el-icon>
          导出数据
        </el-button>
      </div>
    </div>

    <!-- 统计卡片 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :xs="12" :sm="6">
        <el-card class="stats-card">
          <div class="stats-content">
            <div class="stats-info">
              <div class="stats-number">{{ stats.total }}</div>
              <div class="stats-label">总活动数</div>
            </div>
            <el-icon class="stats-icon"><Calendar /></el-icon>
          </div>
        </el-card>
      </el-col>
      
      <el-col :xs="12" :sm="6">
        <el-card class="stats-card">
          <div class="stats-content">
            <div class="stats-info">
              <div class="stats-number">{{ stats.published }}</div>
              <div class="stats-label">已发布</div>
            </div>
            <el-icon class="stats-icon published"><Check /></el-icon>
          </div>
        </el-card>
      </el-col>
      
      <el-col :xs="12" :sm="6">
        <el-card class="stats-card">
          <div class="stats-content">
            <div class="stats-info">
              <div class="stats-number">{{ stats.ongoing }}</div>
              <div class="stats-label">进行中</div>
            </div>
            <el-icon class="stats-icon ongoing"><Clock /></el-icon>
          </div>
        </el-card>
      </el-col>
      
      <el-col :xs="12" :sm="6">
        <el-card class="stats-card">
          <div class="stats-content">
            <div class="stats-info">
              <div class="stats-number">{{ stats.ended }}</div>
              <div class="stats-label">已结束</div>
            </div>
            <el-icon class="stats-icon ended"><CircleCheck /></el-icon>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 搜索和筛选 -->
    <el-card class="filter-card">
      <el-form :model="filters" :inline="true" class="filter-form">
        <el-form-item label="关键词">
          <el-input
            v-model="filters.keyword"
            placeholder="搜索活动标题、描述"
            clearable
            style="width: 200px"
            @keyup.enter="loadActivities"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        
        <el-form-item label="组织者">
          <el-input
            v-model="filters.organizer"
            placeholder="搜索组织者"
            clearable
            style="width: 150px"
          />
        </el-form-item>
        
        <el-form-item label="活动类型">
          <el-select v-model="filters.type" placeholder="选择类型" clearable style="width: 120px">
            <el-option label="学术讲座" value="lecture" />
            <el-option label="文艺演出" value="performance" />
            <el-option label="体育竞赛" value="sports" />
            <el-option label="社会实践" value="practice" />
            <el-option label="志愿服务" value="volunteer" />
            <el-option label="其他" value="other" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="状态">
          <el-select v-model="filters.status" placeholder="选择状态" clearable style="width: 120px">
            <el-option label="草稿" value="draft" />
            <el-option label="已发布" value="published" />
            <el-option label="进行中" value="ongoing" />
            <el-option label="已结束" value="ended" />
            <el-option label="已取消" value="cancelled" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="创建时间">
          <el-date-picker
            v-model="filters.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 240px"
          />
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="loadActivities">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="resetFilters">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 活动列表 -->
    <el-card class="table-card">
      <template #header>
        <div class="table-header">
          <div class="header-title">
            <span>活动列表</span>
            <span class="total-count">（共 {{ pagination.total }} 条）</span>
          </div>
          <div class="header-actions">
            <el-button 
              type="warning" 
              size="small" 
              :disabled="selectedActivities.length === 0"
              @click="batchCancel"
            >
              批量取消
            </el-button>
            <el-button 
              type="danger" 
              size="small" 
              :disabled="selectedActivities.length === 0"
              @click="batchDelete"
            >
              批量删除
            </el-button>
          </div>
        </div>
      </template>
      
      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="5" animated />
      </div>
      
      <div v-else-if="activities.length === 0" class="empty-container">
        <el-empty description="暂无活动数据" />
      </div>
      
      <div v-else>
        <el-table
          :data="activities"
          @selection-change="handleSelectionChange"
          stripe
          style="width: 100%"
        >
          <el-table-column type="selection" width="55" />
          
          <el-table-column label="活动封面" width="100">
            <template #default="{ row }">
              <el-image
                :src="row.coverImage"
                :preview-src-list="[row.coverImage]"
                fit="cover"
                style="width: 60px; height: 40px; border-radius: 4px;"
              >
                <template #error>
                  <div class="image-placeholder">
                    <el-icon><Picture /></el-icon>
                  </div>
                </template>
              </el-image>
            </template>
          </el-table-column>
          
          <el-table-column prop="title" label="活动标题" width="200" show-overflow-tooltip />
          
          <el-table-column label="组织者" width="120">
            <template #default="{ row }">
              <div class="organizer-info">
                <div class="organizer-name">{{ row.organizerName }}</div>
                <div class="organizer-org">{{ row.organizerOrg }}</div>
              </div>
            </template>
          </el-table-column>
          
          <el-table-column label="活动类型" width="100">
            <template #default="{ row }">
              <el-tag :type="getTypeTagType(row.type)" size="small">
                {{ getTypeText(row.type) }}
              </el-tag>
            </template>
          </el-table-column>
          
          <el-table-column label="活动时间" width="160">
            <template #default="{ row }">
              <div class="time-info">
                <div class="start-time">{{ formatDate(row.startTime, 'MM-DD HH:mm') }}</div>
                <div class="end-time">{{ formatDate(row.endTime, 'MM-DD HH:mm') }}</div>
              </div>
            </template>
          </el-table-column>
          
          <el-table-column prop="location" label="活动地点" width="120" show-overflow-tooltip />
          
          <el-table-column label="报名情况" width="100">
            <template #default="{ row }">
              <div class="registration-info">
                <div class="registration-count">
                  {{ row.registrationCount || 0 }}/{{ row.maxParticipants || '∞' }}
                </div>
                <div class="registration-rate">
                  {{ getRegistrationRate(row) }}%
                </div>
              </div>
            </template>
          </el-table-column>
          
          <el-table-column label="状态" width="80">
            <template #default="{ row }">
              <el-tag :type="getStatusType(row.status)" size="small">
                {{ getStatusText(row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          
          <el-table-column prop="createdAt" label="创建时间" width="120">
            <template #default="{ row }">
              {{ formatDate(row.createdAt, 'YYYY-MM-DD') }}
            </template>
          </el-table-column>
          
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="{ row }">
              <el-button type="text" size="small" @click="viewDetail(row)">
                查看
              </el-button>
              <el-button type="text" size="small" @click="viewRegistrations(row)">
                报名
              </el-button>
              <el-button 
                v-if="row.status === 'published' || row.status === 'ongoing'"
                type="text" 
                size="small" 
                @click="cancelActivity(row)"
              >
                取消
              </el-button>
              <el-button type="text" size="small" @click="deleteActivity(row)" class="danger">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="pagination.page"
            v-model:page-size="pagination.size"
            :total="pagination.total"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="loadActivities"
            @current-change="loadActivities"
          />
        </div>
      </div>
    </el-card>

    <!-- 活动详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="活动详情"
      width="800px"
    >
      <div v-if="currentActivity" class="activity-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="活动封面" :span="2">
            <el-image
              :src="currentActivity.coverImage"
              style="width: 200px; height: 120px; border-radius: 8px;"
              fit="cover"
            >
              <template #error>
                <div class="image-placeholder large">
                  <el-icon><Picture /></el-icon>
                  <div>暂无封面</div>
                </div>
              </template>
            </el-image>
          </el-descriptions-item>
          <el-descriptions-item label="活动标题">{{ currentActivity.title }}</el-descriptions-item>
          <el-descriptions-item label="活动类型">
            <el-tag :type="getTypeTagType(currentActivity.type)" size="small">
              {{ getTypeText(currentActivity.type) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="组织者">{{ currentActivity.organizerName }}</el-descriptions-item>
          <el-descriptions-item label="组织/部门">{{ currentActivity.organizerOrg }}</el-descriptions-item>
          <el-descriptions-item label="开始时间">
            {{ formatDate(currentActivity.startTime, 'YYYY-MM-DD HH:mm:ss') }}
          </el-descriptions-item>
          <el-descriptions-item label="结束时间">
            {{ formatDate(currentActivity.endTime, 'YYYY-MM-DD HH:mm:ss') }}
          </el-descriptions-item>
          <el-descriptions-item label="活动地点">{{ currentActivity.location }}</el-descriptions-item>
          <el-descriptions-item label="最大参与人数">
            {{ currentActivity.maxParticipants || '不限' }}
          </el-descriptions-item>
          <el-descriptions-item label="报名截止时间">
            {{ formatDate(currentActivity.registrationDeadline, 'YYYY-MM-DD HH:mm:ss') }}
          </el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getStatusType(currentActivity.status)">
              {{ getStatusText(currentActivity.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">
            {{ formatDate(currentActivity.createdAt, 'YYYY-MM-DD HH:mm:ss') }}
          </el-descriptions-item>
          <el-descriptions-item label="活动描述" :span="2">
            <div class="activity-description" v-html="currentActivity.description"></div>
          </el-descriptions-item>
        </el-descriptions>
        
        <div class="registration-stats">
          <h4>报名统计</h4>
          <el-row :gutter="20">
            <el-col :span="6">
              <div class="stat-item">
                <div class="stat-number">{{ currentActivity.registrationCount || 0 }}</div>
                <div class="stat-label">总报名</div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="stat-item">
                <div class="stat-number">{{ currentActivity.approvedCount || 0 }}</div>
                <div class="stat-label">已通过</div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="stat-item">
                <div class="stat-number">{{ currentActivity.pendingCount || 0 }}</div>
                <div class="stat-label">待审核</div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="stat-item">
                <div class="stat-number">{{ currentActivity.rejectedCount || 0 }}</div>
                <div class="stat-label">已拒绝</div>
              </div>
            </el-col>
          </el-row>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { formatDate } from '@/utils'
import { ElMessage, ElMessageBox } from 'element-plus'
import api from '@/utils/api'
import {
  Download,
  Calendar,
  Check,
  Clock,
  CircleCheck,
  Search,
  Refresh,
  Picture
} from '@element-plus/icons-vue'

const router = useRouter()

const loading = ref(false)
const detailDialogVisible = ref(false)

const stats = reactive({
  total: 0,
  published: 0,
  ongoing: 0,
  ended: 0
})

const filters = reactive({
  keyword: '',
  organizer: '',
  type: '',
  status: '',
  dateRange: null
})

const pagination = reactive({
  page: 1,
  size: 20,
  total: 0
})

const activities = ref([])
const selectedActivities = ref([])
const currentActivity = ref(null)

const getTypeTagType = (type) => {
  const typeMap = {
    lecture: '',
    performance: 'success',
    sports: 'warning',
    practice: 'info',
    volunteer: 'success',
    other: ''
  }
  return typeMap[type] || ''
}

const getTypeText = (type) => {
  const textMap = {
    lecture: '学术讲座',
    performance: '文艺演出',
    sports: '体育竞赛',
    practice: '社会实践',
    volunteer: '志愿服务',
    other: '其他'
  }
  return textMap[type] || type
}

const getStatusType = (status) => {
  const typeMap = {
    draft: 'info',
    published: 'success',
    ongoing: 'warning',
    ended: '',
    cancelled: 'danger'
  }
  return typeMap[status] || ''
}

const getStatusText = (status) => {
  const textMap = {
    draft: '草稿',
    published: '已发布',
    ongoing: '进行中',
    ended: '已结束',
    cancelled: '已取消'
  }
  return textMap[status] || status
}

const getRegistrationRate = (activity) => {
  if (!activity.maxParticipants || activity.maxParticipants === 0) {
    return 0
  }
  const rate = ((activity.registrationCount || 0) / activity.maxParticipants) * 100
  return Math.round(rate)
}

const loadStats = async () => {
  try {
    const response = await api.get('/admin/activities/stats')
    const data = response.data.data
    
    Object.assign(stats, data)
    
  } catch (error) {
    console.error('加载统计数据失败:', error)
  }
}

const loadActivities = async () => {
  try {
    loading.value = true
    
    const params = {
      page: pagination.page,
      size: pagination.size,
      ...filters
    }
    
    if (filters.dateRange && filters.dateRange.length === 2) {
      params.startDate = filters.dateRange[0]
      params.endDate = filters.dateRange[1]
    }
    
    const response = await api.get('/admin/activities', { params })
    const data = response.data.data
    
    activities.value = data.list || []
    pagination.total = data.total || 0
    
  } catch (error) {
    console.error('加载活动列表失败:', error)
    ElMessage.error('加载活动列表失败')
  } finally {
    loading.value = false
  }
}

const resetFilters = () => {
  Object.assign(filters, {
    keyword: '',
    organizer: '',
    type: '',
    status: '',
    dateRange: null
  })
  pagination.page = 1
  loadActivities()
}

const handleSelectionChange = (selection) => {
  selectedActivities.value = selection
}

const viewDetail = async (activity) => {
  try {
    const response = await api.get(`/admin/activities/${activity.id}`)
    currentActivity.value = response.data.data
    detailDialogVisible.value = true
  } catch (error) {
    ElMessage.error('获取活动详情失败')
  }
}

const viewRegistrations = (activity) => {
  router.push(`/admin/registrations?activityId=${activity.id}`)
}

const cancelActivity = async (activity) => {
  try {
    await ElMessageBox.confirm(
      `确定要取消活动 "${activity.title}" 吗？取消后将通知所有已报名的学生。`,
      '确认取消活动',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await api.put(`/admin/activities/${activity.id}/cancel`)
    ElMessage.success('活动取消成功')
    loadActivities()
    loadStats()
    
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('取消活动失败')
    }
  }
}

const deleteActivity = async (activity) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除活动 "${activity.title}" 吗？此操作不可恢复，相关的报名记录也将被删除。`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await api.delete(`/admin/activities/${activity.id}`)
    ElMessage.success('删除成功')
    loadActivities()
    loadStats()
    
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

const batchCancel = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要取消选中的 ${selectedActivities.value.length} 个活动吗？`,
      '确认批量取消',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const ids = selectedActivities.value.map(activity => activity.id)
    await api.put('/admin/activities/batch-cancel', { ids })
    
    ElMessage.success('批量取消成功')
    loadActivities()
    loadStats()
    
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('批量取消失败')
    }
  }
}

const batchDelete = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedActivities.value.length} 个活动吗？此操作不可恢复。`,
      '确认批量删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const ids = selectedActivities.value.map(activity => activity.id)
    await api.delete('/admin/activities/batch', { data: { ids } })
    
    ElMessage.success('批量删除成功')
    loadActivities()
    loadStats()
    
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('批量删除失败')
    }
  }
}

const exportData = async () => {
  try {
    const response = await api.get('/admin/activities/export', {
      params: filters,
      responseType: 'blob'
    })
    
    const blob = new Blob([response.data], {
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    })
    
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = `活动数据_${formatDate(new Date(), 'YYYY-MM-DD')}.xlsx`
    link.click()
    
    window.URL.revokeObjectURL(url)
    ElMessage.success('导出成功')
    
  } catch (error) {
    ElMessage.error('导出失败')
  }
}

onMounted(() => {
  loadStats()
  loadActivities()
})
</script>

<style scoped>
.admin-activity-management {
  max-width: 1400px;
  margin: 0 auto;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding: 24px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 8px;
  color: white;
}

.header-content {
  flex: 1;
}

.page-title {
  font-size: 24px;
  font-weight: 700;
  margin: 0 0 8px 0;
}

.page-subtitle {
  font-size: 14px;
  opacity: 0.9;
  margin: 0;
}

.header-actions {
  display: flex;
  gap: 12px;
  margin-left: 20px;
}

.stats-row {
  margin-bottom: 24px;
}

.stats-card {
  cursor: pointer;
  transition: transform 0.3s ease;
}

.stats-card:hover {
  transform: translateY(-2px);
}

.stats-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
}

.stats-info {
  flex: 1;
}

.stats-number {
  font-size: 24px;
  font-weight: 700;
  color: #303133;
  margin-bottom: 4px;
}

.stats-label {
  font-size: 14px;
  color: #909399;
}

.stats-icon {
  font-size: 28px;
  opacity: 0.3;
  color: #409eff;
}

.stats-icon.published {
  color: #67c23a;
}

.stats-icon.ongoing {
  color: #e6a23c;
}

.stats-icon.ended {
  color: #909399;
}

.filter-card,
.table-card {
  margin-bottom: 20px;
}

.filter-form {
  margin-bottom: 0;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
  color: #303133;
}

.total-count {
  font-size: 12px;
  color: #909399;
  font-weight: normal;
}

.header-actions {
  display: flex;
  gap: 8px;
}

.loading-container,
.empty-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 200px;
}

.image-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 60px;
  height: 40px;
  background: #f5f7fa;
  border-radius: 4px;
  color: #c0c4cc;
  font-size: 12px;
}

.image-placeholder.large {
  width: 200px;
  height: 120px;
  font-size: 14px;
}

.organizer-info {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.organizer-name {
  font-size: 13px;
  color: #303133;
}

.organizer-org {
  font-size: 12px;
  color: #909399;
}

.time-info {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.start-time {
  font-size: 13px;
  color: #303133;
}

.end-time {
  font-size: 12px;
  color: #909399;
}

.registration-info {
  display: flex;
  flex-direction: column;
  gap: 2px;
  align-items: center;
}

.registration-count {
  font-size: 13px;
  color: #303133;
  font-weight: 600;
}

.registration-rate {
  font-size: 12px;
  color: #409eff;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.activity-detail {
  max-height: 600px;
  overflow-y: auto;
}

.activity-description {
  max-height: 200px;
  overflow-y: auto;
  line-height: 1.6;
  color: #606266;
}

.registration-stats {
  margin-top: 24px;
}

.registration-stats h4 {
  margin: 0 0 16px 0;
  color: #303133;
}

.stat-item {
  text-align: center;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 6px;
}

.stat-number {
  font-size: 20px;
  font-weight: 700;
  color: #409eff;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 12px;
  color: #909399;
}

.danger {
  color: #f56c6c !important;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    gap: 16px;
    text-align: center;
  }
  
  .header-actions {
    margin-left: 0;
    flex-direction: column;
  }
  
  .filter-form {
    flex-direction: column;
  }
  
  .filter-form .el-form-item {
    margin-right: 0;
    margin-bottom: 16px;
  }
  
  .table-header {
    flex-direction: column;
    gap: 12px;
    align-items: flex-start;
  }
  
  .header-actions {
    flex-direction: row;
    flex-wrap: wrap;
  }
}
</style>